package com.example.demofdfs.util;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import net.neoremind.sshxcute.core.ConnBean;
import net.neoremind.sshxcute.core.Result;
import net.neoremind.sshxcute.core.SSHExec;
import net.neoremind.sshxcute.task.CustomTask;
import net.neoremind.sshxcute.task.impl.ExecCommand;

public class ShellUtil implements Command {

//	@Value("${app.host}")
	private static String host = "192.168.244.147";
//	@Value("${app.user}")
	private static String user = "root";
//	@Value("${app.password}")
	private static String password = "root";

	private static SSHExec ssh;

	private void init() {
		ConnBean cb = new ConnBean(host, user, password);
		ssh = SSHExec.getInstance(cb);
		ssh.connect();
	}

	public Result exec(String cmd) {
		if (ssh == null)
			init();
		Result result = null;
		CustomTask command = new ExecCommand(cmd);
		try {
//			result = ssh.exec(command);
			result = geResult(ssh, command);
		} finally {
			ssh.disconnect();
		}

		return result;
	}
	
	private ExecutorService executor = Executors.newSingleThreadExecutor();
	private Result geResult(SSHExec ssh, CustomTask command) {
		Callable<Result> callable = new Callable<Result>() {
			@Override
			public Result call() throws Exception {
				return ssh.exec(command);
			}
		};
		Future<Result> future = executor.submit(callable);
		try {
			return future.get(10L, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
		return new Result();
	}

	public static void main(String[] args) {

//		StringBuilder cmd = new StringBuilder("ansible 192.168.225.2 -m shell -a ");
		StringBuilder cmd = new StringBuilder();
//		cmd.append("\"");
//		cmd.append("cal");
		cmd.append("ping 127.0.0.1");
//		cmd.append("ls | grep mkdir | grep mkdir | grep -v  grep | grep -v /temp/ansible | awk '{print \"rmdir ./\" $1}'");
//		cmd.append("\"");
		System.out.println(cmd.toString());
		Result result = new ShellUtil().exec(cmd.toString());

		System.out.println(result.rc);
		System.out.println("sysout : " + result.sysout);
		System.out.println("rc : " + result.rc);
		System.out.println("error_msg : " + result.error_msg);

//		FileUtil.write(result.sysout, "./result.txt");
	}

	@Override
	public void initConnection() {
		// TODO Auto-generated method stub

	}
}
